package algotithm.leetcode.slidingwindow.test56;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @author zhouyanxiang
 * @Date 2021-04-2021/4/12-22:42
 * @Title 56. 合并区间
 */
public class Solution {

    public static void main(String[] args) {
        int[][] intervals = {{1,3}, {2,6}, {8,10},{15,18}};
        Solution solution = new Solution();
        int[][] merge = solution.merge(intervals);
        for (int i = 0; i < merge.length; i++) {
            for (int j = 0; j < merge[0].length; j++) {
                System.out.print(merge[i][j] + " ");
            }
            System.out.println();
        }
    }

    public int[][] merge(int[][] intervals) {
        int n = intervals.length;
        if (n == 1) {
            return intervals;
        }
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });
        List<int[]> merge = new ArrayList<>();
        for (int i = 0;i < n; i++) {
            int l = intervals[i][0];
            int r = intervals[i][1];
            if (merge.size() == 0 || merge.get(merge.size() - 1)[1] < l) {
                merge.add(new int[]{l,r});
            } else {
                merge.get(merge.size() - 1)[1] = Math.max(r,merge.get(merge.size() - 1)[1]);
            }
        }
        return merge.toArray(new int[merge.size()][]);
    }
}